package aleksandar.djuric.offline;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class EncodedFileReadWrite {
	private static String iniString = "FidDataFetcher.ini";
	private static File iniFile = new File(iniString);
	private static BufferedReader in;
	private static PrintWriter out;
	
	public static boolean write(String username, String password)
	{
		boolean isSuccessfull = false;
		try
		{
			out = new PrintWriter(iniFile, "UTF-8");
			out.println(encode(username));
			out.println(encode(password));
			out.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return isSuccessfull;
	}
	
	public static String[] read()
	{
		String[] s = new String[2];
		try {
			in = new BufferedReader(new InputStreamReader(
					new FileInputStream(iniFile),
					"UTF-8"));
			String tmp = in.readLine();
			s[0] = decode(tmp);
			tmp = in.readLine();
			s[1] = decode(tmp);
			in.close();
		} catch (UnsupportedEncodingException e) {
			return null;
		} catch (FileNotFoundException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
		
		return s;
	}
	
	private static String encode(String s)
	{
		StringBuilder builder = new StringBuilder();
		char c = ' ';
		int n = 0;
		for (int i = 0; i < s.length(); i++) {
			c = s.charAt(i);
			n = (int)c;
			builder.append(String.valueOf(n).length());
			builder.append(n);
		}
		return builder.toString();
	}
	
	private static String decode(String s)
	{
		StringBuilder builder = new StringBuilder();
		StringBuilder b = null;
		String c = "";
		char cc = ' ';
		int n = 0;
		int bound = 0;
		for (int i = 0; i < s.length(); i++) {
			c = String.valueOf(s.charAt(i));
			n = Integer.valueOf(c);
			i++;
			bound = n + i;
			b = new StringBuilder();
			for (; i < bound; i++) {
				b.append(s.charAt(i));
			}
			cc = (char)(Integer.parseInt(b.toString()));
			builder.append(cc);
			i--;
		}
		return builder.toString();
	}
	
	public static void deleteIni()
	{
		iniFile.delete();
	}

	public static void main(String[] args) {
		EncodedFileReadWrite.write("jeЋan123456789;", "dva!@#$%&^()");
		System.out.println(Arrays.toString(EncodedFileReadWrite.read()));
	}
}
